/**
 * Created by henian.xu on 2018/11/28.
 * 公用工具类库
 */

const autoIncrement = 0;

/**
 * 创建不重复的 Id
 * @param prefix
 * @returns {string}
 */
export function getUniqueId(prefix = '') {
    this.autoIncrement++;
    const cDate = new Date().getTime();
    const offDate = new Date(2010, 1, 1).getTime();
    const offset = cDate - offDate;
    return prefix + parseFloat(offset + '').toString(16) + autoIncrement;
}

/**
 * 创建不重复 Key
 * @param t
 * @returns {string}
 */
export function getKey(t = 'xxxxxxxx') {
    // const t  = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
    return t.replace(/[xy]/g, function(c) {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}

/**
 * 数据转 map
 * @param arr
 * @param Object
 * @param prop
 * @returns {*}
 */
export function listToMap(arr, { prop = { id: 'id', children: 'children' }, Object = {} } = {}) {
    return arr.reduce((p, c) => {
        if (Array.isArray(c)) {
            listToMap(c, { Object: p, prop });
        } else {
            p[c[prop.id]] = c;
            if (c[prop.children]) {
                listToMap(c[prop.children], { Object: p, prop });
            }
        }
        return p;
    }, Object);
}
